package com.ttxs.common.core.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;

import java.util.Date;
import java.util.HashMap;

public class JwtTokenUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    // 密钥
    private static String secret = "1a3*L(2x&G";
    //签发者
    private static final String ISS = "ttxs.com";

    public static String createToken(HashMap<String, Object> claims, Date expiration) {
        return Jwts.builder()
                // 签名需要使用Base64.encode编码，否则稍微改动密钥或盐签名不会失效（Base64.decode可能会得到相同的值）
                .signWith(SignatureAlgorithm.HS512, TextCodec.BASE64.encode(secret))
                .setClaims(claims)
                .setIssuer(ISS)
                .setSubject("ttxs-jwt")
                .setIssuedAt(new Date())
                .setExpiration(expiration)
                .compact();
    }

    public static String createRefreshToken(Date expiration) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", Math.random());
        return Jwts.builder()
                // 签名需要使用Base64.encode编码，否则稍微改动密钥或盐签名不会失效（Base64.decode可能会得到相同的值）
                .signWith(SignatureAlgorithm.HS512, TextCodec.BASE64.encode(secret))
                .setIssuer(ISS)
                .setIssuedAt(new Date())
                .setClaims(map)
                .setExpiration(expiration)
                .compact();
    }

    /**
     * 给token续期
     * @param token - valid token
     * @param expiration - in minutes
     * @return
     */
    public static String refreshToken(String token, int expiration) {
        Claims claims = getTokenBody(token);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, TextCodec.BASE64.encode(secret))
                .setClaims(claims)
//                .setExpiration(new Date(claims.getExpiration().getTime() + expiration * 60 * 1000))
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 60 * 1000))
                .compact();
    }

    // 是否已过期
    public static boolean isExpiration(String token) {
        return getTokenBody(token).getExpiration().before(new Date());
    }

    public static Claims getTokenBody(String token)  {
        return Jwts.parser()
                .setSigningKey(TextCodec.BASE64.encode(secret))
                .parseClaimsJws(token)
                .getBody();
    }



}